﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;


// Additional Libraries
using Microsoft.Phone.Notification;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Controls.Maps;
using Microsoft.Phone.Controls.Maps.Core;
using System.Device.Location;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Net.NetworkInformation;

using LocalDatabase.Model;
using LocalDatabase.ViewModel;
using System.Windows.Controls.Primitives;

namespace FindMe
{
    

    public partial class Main : PhoneApplicationPage
    {
        #region Comentario de ramon luis
        /// <summary>
		/// Find Me
		/// Dev: 			Ramon Luis De Jesus
		/// Start Date:		4/15/2012
		/// End Date:
		/// Platform:		windows phone 7.1
		/// 
		/// Description:	Locate friends, chat, emotions in seconds.
		/// 
		/// </summary>
		/// 
        /// 
        #endregion
        // <-- Map Global-->
        MapLayer imageLayer;
       ProgressIndicator progress;
        // <-- End Map Global -->

        FindMeFriendServiceReference.FindMeFriendServiceClient serviceClient;
        IsolatedStorageSettings settings;

        public Color ApplicationBarColor = Color.FromArgb(255, 118, 118, 118);
        
        
        public Main()
        {
            InitializeComponent();

            hubTileProfileBanner.Title = App.FullName;

            // Create the ViewModel object.
            App._FindMeFriendsViewModel = new FindMeFriendsViewModel();
            //App._FavoriteLocationsViewModel = new FavoriteLocationsViewModel();

            // Query the local database and load observable collections.
            App._FindMeFriendsViewModel.LoadFriendsFromDatabase();
            App._FavoriteLocationsViewModel.LoadFavLocationsFromDatabase();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            //this.DataContext = App.todoViewModel;
            this.Loaded += new RoutedEventHandler(Main_Loaded);


            //<-- Public Map Vars -->


            ///Create a layer to contain the pushpin images.

            imageLayer = new MapLayer();
            map.Children.Add(imageLayer);
            //<--End Public Map Vars -->


            //<-- Progress bar and clock colors -->
            SystemTray.SetIsVisible(this, true);
            SystemTray.SetOpacity(this, 0.0);
            SystemTray.SetBackgroundColor(this, Colors.Black);
            SystemTray.SetForegroundColor(this, Colors.White);
            progress = new ProgressIndicator();
            progress.IsIndeterminate = true;
            progress.Text = "Loading";
            SystemTray.SetProgressIndicator(this, progress);

            //<-- End progress bar and clock colors -->


            if (!DeviceNetworkInformation.IsNetworkAvailable && !DeviceNetworkInformation.IsWiFiEnabled)
            {
                MessageBox.Show("No Cellular or Wi-Fi network is available! Please verify your network connectivity.", "Network Error", MessageBoxButton.OK);
                while (NavigationService.RemoveBackEntry() != null) ;
            }

            serviceClient = new FindMeFriendServiceReference.FindMeFriendServiceClient();
            settings = IsolatedStorageSettings.ApplicationSettings;

            if (App.pushChannel != null)
            {
                App.pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(pushChannel_ShellToastNotificationReceived);
            }
        }

        //<-- Map Size for Orientation Landscape-->
        protected override void OnOrientationChanged(OrientationChangedEventArgs e)
        {
            base.OnOrientationChanged(e);

            if (((e.Orientation == PageOrientation.LandscapeLeft) || (e.Orientation == PageOrientation.LandscapeRight)) && PivotPages.SelectedItem == MapPage)
            {
                NavigationService.Navigate(new Uri(App.PathFullMap, UriKind.Relative));
            }
        }

        // <-- Map END for Orientation -- >

        void pushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
        {
            if (NavigationService.CurrentSource == new Uri("/Main.xaml", UriKind.Relative))
            {
                MessageBox.Show("MessageReceived!");
            }
        }

        // Load data for the ViewModel Items
        private void Main_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
         
        }




        // Back OVERRIDE

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            //Sencillo este while elimina todos las posibles backs!!! Luego hace el comando de back tirandote al OS. 
            while (NavigationService.RemoveBackEntry() != null) ;

        }

		///<-- findMe page configuration -->

        //Adds latitude and longitude :D
        /*public string getMyGPS()
        {
            string MyGPS;
            MyGPS = getGPS; 
			//glatitude() + "," + glongitude();
            return MyGPS;
        }

        
		//Function returns latitude
        private double glatitude()
        {

            double latitude;
            //Inicia la clase que ubica al telefono.
            GeoCoordinateWatcher myWatcher = new GeoCoordinateWatcher();
            var myGPSPosition = myWatcher.Position;


            latitude = myGPSPosition.Location.Latitude;


            if (myGPSPosition.Location.IsUnknown)
            {

                latitude = 18.24;
                return latitude;

            }

            return latitude;
        }

        //Function returns latitude
        private double glongitude()
        {
            double longitude;
            //Inicia la clase que ubica al telefono.
            GeoCoordinateWatcher myWatcher = new GeoCoordinateWatcher();
            var myGPSPosition = myWatcher.Position;

            longitude = myGPSPosition.Location.Longitude;

            if (myGPSPosition.Location.IsUnknown)
            {

                longitude = -66.10;


                return longitude;
            }

            return longitude;
        }*/
        
        private void findBtn_GotFocus(object sender, System.Windows.RoutedEventArgs e)
        {
            // TODO: Add event handler implementation here.
        }


        private void findBtn_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            LocationInitialize();
        }

        //Send Location btn
        private void sendBtn_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {

            LabeledMapLocation end = new LabeledMapLocation();
            end.Label = "18.24, -66.10";

            BingMapsDirectionsTask x = new BingMapsDirectionsTask();

            x.End = end;
            x.Show();

        }

        ///<-- End findMe page configuration -->
		//<--Map-->


        ///<-- friends Map Configuration -->

        private GeoCoordinateWatcher _geo;
        public GeoPositionAccuracy Accuracy = GeoPositionAccuracy.High;
        private string _mode = "Road";

        private void PhoneApplicationPageLoaded(object sender, RoutedEventArgs e)
        {

            LocationInitialize();
        }

        

        private void LocationInitialize()
        {


           progress.IsVisible = true;
			
            // Reinitialize the GeoCoordinateWatcher
            _geo = new GeoCoordinateWatcher(Accuracy) { MovementThreshold = 20 };

            // Add event handlers for StatusChanged and PositionChanged events
            _geo.StatusChanged -= GeoStatusChanged;
            _geo.PositionChanged -= GeoPositionChanged;

            _geo.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(GeoStatusChanged);
            _geo.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(GeoPositionChanged);

            // Start data acquisition
            _geo.Start();
           progress.IsVisible = false;
        }

        /*private void BtnAccuracyClick(object sender, RoutedEventArgs e)
        {
            Accuracy = Accuracy == GeoPositionAccuracy.Default ? GeoPositionAccuracy.High : GeoPositionAccuracy.Default;
            btnAccuracy.Content = Accuracy == GeoPositionAccuracy.High ? "Default Accuracy" : "High Accuracy";
            LocationInitialize();
        }*/

    
	
        void GeoPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            /*
            // Update the TextBlocks to show the current location
            txtLatitude.Text = e.Position.Location.Latitude.ToString("0.000");
            txtLongitude.Text = e.Position.Location.Longitude.ToString("0.000");
			txtLocation.Text="Location: \r\n"+ txtLatitude.Text  +","+ txtLongitude.Text;
             */
            var cor = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude);

            //Using the current coordinates define the Map center to those coordinates.
            map.Center = cor;
            map.ZoomLevel = 15;
			
			/// <-- Start Image for center of Map -->
			
			// Create a pushpin to put at the center of the view.
            
            Pushpin pin1 = new Pushpin();
           
                pin1.Location = cor;
            //Clears other (pin1)    
                map.Children.Clear();
            //----------------
                map.Children.Add(pin1);

                App.UserCoordinates= e.Position.Location.Latitude.ToString("0.000") + "," + e.Position.Location.Longitude.ToString("0.000");

            // Use the Windows Phone pushpin style from App.xaml.
            pin1.Style = (Style)(Application.Current.Resources["PushpinStyle"]);
            pin1.PositionOrigin = PositionOrigin.BottomLeft;
            pin1.Content = "Me";

            ///<! --- Second Pin or friends pins

            Pushpin pin2 = new Pushpin();
            pin2.Location = new GeoCoordinate(18.24, -66.10);
            map.Children.Add(pin2);
            
            // Content of pin
            pin2.Content = "Hector Asencio";

            //Event for pin
            pin2.MouseLeftButtonUp += new MouseButtonEventHandler(pin2_MouseLeftButtonUp);
			/// <---End Second Pin-->


			/*
			 // Define the image to use as the pushpin icon.
            Image pinImage = new Image();

            //Define the URI location of the image.
            pinImage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("bluepushpin.png", UriKind.Relative));
            
            //Define the image display properties.
            pinImage.Opacity = 0.8;
            pinImage.Stretch = System.Windows.Media.Stretch.None;

            // Put the image at the center of the view.
            PositionOrigin position = PositionOrigin.Center;
            imageLayer.AddChild(pinImage, cor, position);
				*/		
			/// <-- End Image for center of Map -->
			
        }

        void GeoStatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
           /* this.Dispatcher.BeginInvoke(() =>
            {
                switch (e.Status)
                {
                    case GeoPositionStatus.Disabled:
                        // The location service is disabled or unsupported.
                        // Alert the user
                        txtStatus.Text = "location is unsupported on this device";
                        break;
                    case GeoPositionStatus.Initializing:
                        // The location service is initializing.
                        // Disable the Start Location button
                        txtStatus.Text = "initializing location service," + Accuracy;
                        break;
                    case GeoPositionStatus.NoData:
                        // The location service is working, but it cannot get location data
                        // Alert the user and enable the Stop Location button
                        txtStatus.Text = "data unavailable," + Accuracy;
                        break;
                    case GeoPositionStatus.Ready:
                        // The location service is working and is receiving location data
                        // Show the current position and enable the Stop Location button
                        txtStatus.Text = "receiving data, " + Accuracy;
                        break;

                }
            });*/
        }

        /// <summary>
        /// Pins Actions
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void pin2_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/contact.xaml", UriKind.Relative));
        }
        //<!-- End Pin Actions -->




        /// <summary>
        /// NavBar Menu Items
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sync_Click(object sender, EventArgs e)
        {
            Accuracy = Accuracy == GeoPositionAccuracy.Default ? GeoPositionAccuracy.High : GeoPositionAccuracy.Default;
            //btnAccuracy.Content = Accuracy == GeoPositionAccuracy.High ? "Default Accuracy" : "High Accuracy";
            LocationInitialize();
        }

        private void mapView_Click(object sender, EventArgs e)
        {
           progress.IsVisible = true;
            ApplicationBarMenuItem btnMapView = (ApplicationBarMenuItem)ApplicationBar.MenuItems[0];

            if (_mode == "Road")
            {
                map.Mode = new AerialMode();
                _mode = "Aerial";
               btnMapView.Text = "change map to road view";
            }
            else
            {
                
                map.Mode = new RoadMode();
                _mode = "Road";
                btnMapView.Text = "change map to aerial view";

            }
           progress.IsVisible = false;
        }
        /// End NavBar Menu Items
        
        private void TEMP_Tap(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/chat.xaml", UriKind.Relative));
        }

        private void settings_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(App.PathSettings, UriKind.Relative));
        }

        private void pref_Click(object sender, EventArgs e)
        {

        }

        private void logout_Click(object sender, EventArgs e)
        {
            progress.IsVisible = true;
            string username = settings["Username"].ToString();
            Guid sessionToken = (Guid)settings["SessionToken"];

            serviceClient.LogOffAsync(username, sessionToken);
            settings["SessionToken"] = new Guid();
            settings.Save();
            progress.IsVisible = false;
            NavigationService.Navigate(new Uri(App.PathLogin, UriKind.Relative));
        }


        private void btnHome_Tap(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri(App.PathMain, UriKind.Relative));
        }

        private void btnInbox_Tap(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri(App.PathConversations, UriKind.Relative));
        }

        private void btnRequests_Tap(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri(App.PathNotifications, UriKind.Relative));
        }

    

///-- AppBar for pages


        private void PivotPages_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
           if (PivotPages.SelectedItem == ProfilePage)
            {
                SetAppBarProfile();
            }
            else if (PivotPages.SelectedItem == FriendsPage)
            {
                SetAppBarFriends();
            }
            else if (PivotPages.SelectedItem == MapPage)
            {
                SetAppBarMap();
            }
        }

        private void SetAppBarProfile()
        {
            ApplicationBar = new ApplicationBar()
            {
                IsVisible = true,
                Mode = ApplicationBarMode.Minimized,
                IsMenuEnabled = true,
                Opacity = 100,
                BackgroundColor = ApplicationBarColor
            };

            ApplicationBarIconButton appFindme = new ApplicationBarIconButton()
            {
                IconUri = new Uri("/Icons/0appbar.findme.png", UriKind.Relative),
                Text = "find.Me",
                IsEnabled = true
            };
            ApplicationBar.Buttons.Add(appFindme);
            appFindme.Click += new EventHandler(sync_Click);

            ApplicationBarMenuItem settings = new ApplicationBarMenuItem();
            settings.Text = "settings";
            ApplicationBar.MenuItems.Add(settings);
            settings.Click +=new EventHandler(settings_Click);

            ApplicationBarMenuItem logout = new ApplicationBarMenuItem();
            logout.Text = "log out";
            ApplicationBar.MenuItems.Add(logout);
            logout.Click += new EventHandler(logout_Click);
        }

        private void SetAppBarFriends()
        {
            ApplicationBar = new ApplicationBar()
            {
                IsVisible = true,
                Mode = ApplicationBarMode.Minimized,
                IsMenuEnabled = true,
                Opacity = 100,
                BackgroundColor= ApplicationBarColor
            };

            ApplicationBarIconButton cancel = new ApplicationBarIconButton()
            {
                IconUri = new Uri("/Icons/0appbar.cancel.png", UriKind.Relative),
                Text = "Cancel",
                IsEnabled = true
            };
            ApplicationBar.Buttons.Add(cancel);

            ApplicationBarMenuItem settings = new ApplicationBarMenuItem();
            settings.Text = "settings";
            ApplicationBar.MenuItems.Add(settings);
            settings.Click +=new EventHandler(settings_Click);

            ApplicationBarMenuItem logout = new ApplicationBarMenuItem();
            logout.Text = "log out";
            ApplicationBar.MenuItems.Add(logout);
            logout.Click += new EventHandler(logout_Click);
        }

        private void SetAppBarMap()
        {
            ApplicationBar = new ApplicationBar()
            {
                IsVisible = true,
                Mode = ApplicationBarMode.Default,
                IsMenuEnabled = true,
                Opacity = 100,
                BackgroundColor = ApplicationBarColor
            };

            
            ApplicationBarIconButton appFindme = new ApplicationBarIconButton()
            {
                IconUri = new Uri("/Icons/0appbar.findme.png", UriKind.Relative),
                Text = "find.Me",
                IsEnabled = true
            };
            ApplicationBar.Buttons.Add(appFindme);
            appFindme.Click+=new EventHandler(sync_Click);

            ApplicationBarIconButton appMapView = new ApplicationBarIconButton()
            {
                IconUri = new Uri("/Icons/0appbar.mapview.png", UriKind.Relative),
                Text = "view",
                IsEnabled = true
            };
            ApplicationBar.Buttons.Add(appMapView);
            appMapView.Click += new EventHandler(mapView_Click);
           
            
            ApplicationBarIconButton appAddLocation = new ApplicationBarIconButton()
            {
                IconUri = new Uri("/Icons/0appbar.findmeadd.png", UriKind.Relative),
                Text = "add this location",
                IsEnabled = true
                


            };
            ApplicationBar.Buttons.Add(appAddLocation);

            appAddLocation.Click+= new EventHandler(appAddLocation_Click);

          
            ApplicationBarIconButton appFullscreen = new ApplicationBarIconButton()
            {
                IconUri = new Uri("/Icons/0appbar.zoom.png", UriKind.Relative),
                Text = "fullscreen",
                IsEnabled = true
            };
            ApplicationBar.Buttons.Add(appFullscreen);
            appFullscreen.Click +=new EventHandler(appFullscreen_Click);          
           
            ApplicationBarMenuItem settings = new ApplicationBarMenuItem();
            settings.Text = "settings";
            ApplicationBar.MenuItems.Add(settings);
            settings.Click+=new EventHandler(settings_Click);

            ApplicationBarMenuItem logout = new ApplicationBarMenuItem();
            logout.Text = "log out";
            ApplicationBar.MenuItems.Add(logout);
            logout.Click += new EventHandler(logout_Click);
        }



        private void txtNewStatus_MouseEnter(object sender, MouseEventArgs e)
        {
            if (txtStatus.Text == "What are you doing?")
            {
                txtStatus.Text = String.Empty;
                txtStatus.Foreground = new SolidColorBrush(Colors.Black);
            }
        }

        private void txtNewStatus_MouseLeave(object sender, MouseEventArgs e)
        {
            if (txtStatus.Text == String.Empty)
            {
                txtStatus.Text = "What are you doing?";
                txtStatus.Foreground = new SolidColorBrush(Colors.Black);
            }
            else
            {
                try
                {
                    string username = settings["Username"].ToString();
                    Guid sessionToken = (Guid)settings["SessionToken"];

                    serviceClient.PostStatusUpdateAsync(username, sessionToken, txtStatus.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void appFullscreen_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(App.PathFullMap, UriKind.Relative));
        }

        private void btnShare_Tap(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri(App.PathShare, UriKind.Relative));
        }

        private void btnGotoHome_Tap(object sender, RoutedEventArgs e)
        {
            try
            {
                LabeledMapLocation end = new LabeledMapLocation()
                    {
                        Label = "18.24, -66.10"
                    };

                BingMapsDirectionsTask x = new BingMapsDirectionsTask()
                {
                    End = end
                };
                x.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnFavorites_Tap(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri(App.PathFavLocations, UriKind.Relative));
        }

        private void Acontact_Tap(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri(App.PathContact, UriKind.Relative));
        }


       
        private void appAddLocation_Click(object sender, EventArgs e)
        {
            //trying to call the button
            Popup locationName;
            locationName = new Popup();
            locationName.IsOpen = true;
            locationName.Child = new locationName();
            locationName.HorizontalOffset = 0;
            locationName.VerticalOffset = -150;
            locationName.Closed += (s1, e1) =>
            { };

       }
        //-- End AppBar for pages
      
    }
}